package com.ccp.dev.system.service;

import com.ccp.dev.core.basic.api.ISysUserService;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.system.configuration.CustomPwdEncoder;
import com.ccp.dev.system.dao.SysUserDao;
import com.ccp.dev.system.model.*;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.util.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;

/**
 * 用戶管理service
 * @author  y
 */
@Service
public class SysUserService extends BaseService<SysUser> implements ISysUserService {
    @Resource
    SysUserDao sysUserDao;
    @Resource
    UserPositionService userPositionService;
    @Resource
    UserUnderService userUnderService;
    @Resource
    UserRoleService userRoleService;
    @Resource
    SysRoleService sysRoleService;
    @Resource
    SysTenantDynamicDataService sysTenantDynamicDataService;
    @Resource
    SysOrgService sysOrgService;
    @Resource
    SysTenantOrgService sysTenantOrgService;
    @Resource
    SessionRegistry sessionRegistry;
    @Resource
    PwdStrategyService pwdStrategyService;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private SysPropertyService propertyService;
    @Resource
    private DictionaryService dictionaryService;

    @Value("${mybatis.configuration.database-id}")
    String dataSourceType;

    @Value("${server.imModel.load}")
    private Boolean loadIm = false;

    /**
     * 根据账号获取用户
     * @param account  用户账号
     * @return SysUser
     */
    public SysUser getByAccount(String account){
       return this.sysUserDao.getByAccount(account);
    }

    /**
     * 根据account获取用户列表，包含路径信息
     * 2020-05-26 jyq添加，由于同一租户下可存在相同的账户名称
     * @param account 账户
     * @return list
     */
    public List<SysUser> queryByAccount(String account){
        List<SysUser> userList = sysUserDao.queryByAccount(account);
        if(BeanUtils.isEmpty(userList) || userList.size()==1){
            //若用户不存在或只存在一个则直接返回用户列表
            return userList;
        }else {
            //返回带组织路径的用户列表
            return sysUserDao.queryByAccountWithOrgPath(account);
        }
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser sysUser = this.getOneById(s);
        if(null == sysUser){
            throw new UsernameNotFoundException("用户不存在！");
        }
        return sysUser;
    }

    /**
     * 登录成功后修改状态
     * @param userId 用户id
     * @param ip    登录ip
     */
    @Transactional(rollbackFor = Exception.class)
    public void loginSuccessSet(String userId,String ip){
        //登录成功后清空失败次数
        updateMissNumber(userId,Short.parseShort("0"));
        //更新用户状态为在线
        upOnlineStatusById(userId,SysUser.ISONLINE_Y);
        //更新用户ip
        updCurrIpById(userId,ip);
    }

    /**
     * 退出成功后修改状态
     * @param userId 用户id
     */
    @Transactional(rollbackFor = Exception.class)
    public void logoutSuccessSet(String userId){
        //更新用户状态为离线
        upOnlineStatusById(userId,SysUser.ISONLINE_N);
        //更新用户ip
        updCurrIpById(userId,"");
    }

    /**
     * 重置密码
     * @param userId    用户id
     * @param newPassword  用户密码  明文
     * @param oldPassword 旧密码
     */
    @Transactional(rollbackFor = Exception.class)
    public void modifyPwd(String userId,String newPassword,String oldPassword) throws Exception{
        pwdStrategyService.checkStrategy(newPassword);
        CustomPwdEncoder customPwdEncoder = new CustomPwdEncoder();
        SysUser sysUser = this.getOneById(userId);
        //旧密码
        String oPassword = customPwdEncoder.encode(oldPassword);
        if(!oPassword.equals(sysUser.getPassword())){
            throw new Exception("sysUser.editUser.modifyPwdWarning");
        }
        //新密码
        String nPassword = customPwdEncoder.encode(newPassword);
        Map<String,Object> map = new HashMap<>(3);
        map.put("userId",userId);
        map.put("password",nPassword);
        map.put("pwdUpdTime",new Date());
        this.sysUserDao.updatePwd(map);
    }


    /**
     * 重置密码
     * @param userId    用户id
     * @param newPassword  用户密码  明文
     */
    @Transactional(rollbackFor = Exception.class)
    public void resetPwd(String userId,String newPassword) throws Exception{
        pwdStrategyService.checkStrategy(newPassword);
        CustomPwdEncoder customPwdEncoder = new CustomPwdEncoder();
        //新密码
        String nPassword = customPwdEncoder.encode(newPassword);
        Map<String,Object> map = new HashMap<>(3);
        map.put("userId",userId);
        map.put("pwdUpdTime",new Date());
        map.put("password",nPassword);
        this.sysUserDao.updatePwd(map);
    }

    /**
     * 设置领导
     * @param userIds
     */
    @Transactional(rollbackFor = Exception.class)
    public void setLeaderByIds(String[] userIds) {
        sysUserDao.setLeaderByIds(userIds);
    }

    /**
     * 取消领导
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    public void delLeader(String userId) {
        sysUserDao.delLeader(userId);
    }


    /**
     * 置为离线
     * @param userId 用户id
     */
    @Transactional(rollbackFor = Exception.class)
    public void setOffline(String userId){
        removeSession(this.getOneById(userId));
        Map<String,Object> map = new HashMap<>(3);
        map.put("userId",userId);
        map.put("isOnline",SysUser.ISONLINE_N);
        map.put("currIp","");
        this.sysUserDao.upOnlineStatusById(map);
        this.sysUserDao.updCurrIpById(map);
    }

    /**
     * 用户状态初始化
     */
    @Transactional(rollbackFor = Exception.class)
    public void userStatusInit(){
        Map<String,Object> map = new HashMap<>(2);
        map.put("isOnline",SysUser.ISONLINE_N);
        map.put("currIp","");
        this.sysUserDao.upOnlineStatusById(map);
        this.sysUserDao.updCurrIpById(map);
    }

    /**
     * 删除session
     * @param user 用户
     */
    public void removeSession(SysUser user) {
        List<Object> objectList = sessionRegistry.getAllPrincipals();
        for (Object userDetail : objectList) {
            String account = ((SysUser) userDetail).getAccount();
            if (account.equals(user.getAccount())) {
                removeSession(userDetail);
                break;
            }
        }

    }

    /**
     * 删除session
     *
     * @param principal 主要的
     */
    private void removeSession(Object principal) {
        //根据principal获取所有没有过期的session 并设置为过期
        List<SessionInformation> sessionInformations = sessionRegistry .getAllSessions(principal, false);
        for (SessionInformation sessionInformation : sessionInformations) {
            sessionInformation.expireNow();
        }
    }

    /**
     * 获取在线用户
     * @return listModel
     */
    public List<SysUser> getOnLineUsers(){
        return (List<SysUser>)(Object)sessionRegistry.getAllPrincipals();
    }

    /**
     * 设置用户和角色的关联关系
     * @param sysUser 参数
     */
    @Transactional(rollbackFor = Exception.class)
    public void setupState(SysUser sysUser) throws Exception{
        String userId = sysUser.getUserId();
        boolean isContain = this.sysRoleService.isContainThreeRole(userId);
        if(isContain){
            throw  new Exception("sysUser.editUser.threeUserWarning");
        }
        sysUser.setUpdateTime(new Date());
        sysUser.setUpdateBy(ContextUtil.getCurrentUserId());
        this.sysUserDao.updateStatus(sysUser);
        // 角色数组
        String[] roleIds = sysUser.getRoleId();
        this.userRoleService.delByUserId(userId);
        this.userRoleService.userAddRole(userId,roleIds);
    }

    /**
     * 删除用户以及关联关系
     * @param ids id数组
     */
    @Transactional(rollbackFor = Exception.class)
    public void delUserByIds(String[] ids) throws Exception{
        if(null == ids){
            throw  new Exception("delete.failure");
        }
        boolean isContainThreeRole = false;
        for(String id : ids){
            boolean isContain = this.sysRoleService.isContainThreeRole(id);
            if(isContain){
                isContainThreeRole = true;
                continue;
            }
            this.delById(id);
            this.userPositionService.delByUserId(id);
            this.userUnderService.delByUpOrDown(id);
            this.userRoleService.delByUserId(id);
        }

        if(ids.length == 1){
            if(isContainThreeRole){
                throw  new Exception("sysUser.delUser.threeUserWarning");
            }
        }else{
            if(isContainThreeRole){
                throw  new Exception("sysUser.delUser.warning");
            }
        }
    }

    /**
     * 判断账号是否存在
     * @param account 账号
     * @return true 存在  false 不存在
     */
    public boolean isAccountExist(String account){
        int n = this.sysUserDao.isAccountExist(account);
        return  n > 0;
    }

    /**
     * 通过account和tenantId判断账号是否存在
     *
     * @param account  账号
     * @param tenantId 租户账号
     * @return true 存在  false 不存在
     */
    public boolean isAccountExist(String account, String tenantId) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("account", account);
        map.put("tenantId", tenantId);

        int n = this.sysUserDao.isAccountExistByTenantId(map);
        return n > 0;
    }

    /**
     * 保存或更新用户信息
     * @param sysUser 用户model
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUser sysUser) throws Exception{
        //用户id
        String userId = sysUser.getUserId();
        // 组织Id 包含代表点击树后添加
        String orgId = sysUser.getOrgId();
//        // 岗位Id数组
//        String[] posIds = sysUser.getPosId();
//        // 主要负责人数组
//        String[] personCharges = sysUser.getIsCharge();
//        // 主要岗位Id
//        String mainPosts = sysUser.getIsPrimary();
        // 上级Id数组
        String[] superiorIds = sysUser.getSuperiorIds();
        //获取当前系统时间
        Date date = new Date();
        //获取当前登录人id
        String curUserId = ContextUtil.getCurrentUserId();

        boolean isAdd = false;
        if(StringUtil.isEmpty(userId)){
            isAdd = true;

            String tenantId;
            if (StringUtil.isNotEmpty(orgId)) {
                if (StringUtil.isNotEmpty(sysUser.getTenantId())) {
                    tenantId = sysUser.getTenantId();
                } else {
                    tenantId = sysOrgService.getTenantItByOrgId(orgId.split(",")[0]);
                }
            } else {
                tenantId = ContextUtil.getCurrentUserTenantId();
            }


            //新增时需要判断账号是否已经存在,更新时不需要判断因为不允许修改account
            //wangbo 2020-4-16
            // 不同租户下，应该允许添加相同的“账号”，即account允许相同。在相同租户下，不允许建立相同的“账号”。
            String account = sysUser.getAccount();
            boolean accountExist = this.isAccountExist(account, tenantId);
            if (accountExist) {
                throw new Exception("sysUser.editUser.accountWarning");
            }


//            //新增时需要判断账号是否已经存在,更新时不需要判断因为不允许修改account
//            String account = sysUser.getAccount();
//            boolean accountExist = this.isAccountExist(account);
//            if(accountExist){
//                throw new Exception("sysUser.editUser.accountWarning");
//            }
            //新增
            String password = sysUser.getPassword();
            CustomPwdEncoder customPwdEncoder = new CustomPwdEncoder();
            String enPassword = customPwdEncoder.encode(password);
            sysUser.setPassword(enPassword);
            userId = UUIDUtils.getUUIDFor32();
            sysUser.setUserId(userId);
            sysUser.setIsLock(SysUser.UN_LOCKED);
            sysUser.setIsExpired(SysUser.UN_EXPIRED);
            sysUser.setIsOnline(SysUser.ISONLINE_N);
            sysUser.setStatus(SysUser.STATUS_OK);
            sysUser.setPwdUpdTime(date);
            sysUser.setFromType(SysUser.FROMTYPE_DB);
            //新增用户时默认密级从系统属性中读取系统属性中没有默认从model里读取
            //String Level = PropertyUtil.getByAlias("userSec");
            //todo  密级需要修改
            /*String level = "1";
            sysUser.setPrivacyLevel(StringUtil.isEmpty(level)? SysUser.DEFAULT_PRIVACYLEVEL:Integer.parseInt(level));*/
            sysUser.setPrivacyLevel(StringUtil.isEmpty(sysUser.getPrivacyLevel()) ? SysUser.DEFAULT_PRIVACYLEVEL : sysUser.getPrivacyLevel());
            sysUser.setCreateBy(curUserId);
            sysUser.setCreateTime(date);
            sysUser.setTenantId(tenantId);

            this.sysUserDao.add(sysUser);

//            String tenantId;
//            if(StringUtil.isNotEmpty(orgId)){
//                tenantId = sysTenantOrgService.getTenantIdByOrgId(orgId);
//            }else{
//                tenantId = ContextUtil.getCurrentUserTenantId();
//            }
            //增加租户用户映射
            sysTenantDynamicDataService.addSysTenantDynamicData(userId,tenantId,SysUser.class);

            //若当前租户中存在默认角色则在添加用户时直接绑定默认角色
            SysRole sysRole = sysRoleService.queryIsDefaultRole(tenantId);
            if(BeanUtils.isNotEmpty(sysRole)){
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(sysRole.getRoleId());
                userRole.setUserRoleId(UUIDUtils.getUUIDFor32());
                userRoleService.add(userRole);
            }

        }else{
            //判断当前用户是否包含三员角色  包含：throw
            boolean isContain = this.sysRoleService.isContainThreeRole(userId);
            if(isContain){
                throw new Exception("sysUser.editUser.threeUserWarning");
            }
            //修改
            sysUser.setUpdateBy(curUserId);
            sysUser.setUpdateTime(date);

            SysOrg sysOrg = sysOrgService.getSysOrgById(sysUser.getPrimayOrgId());


            //检查租户是否存在相同账户
            List<SysUser> sysUserList = this.findByAccountAndTenantId(sysUser.getAccount(), sysOrg.getTenantId());

            if(sysUserList.size() > 1){
                //throw new Exception("该租户下存在相同帐户");
                throw new Exception("sysUser.editUser.accountWarningOrg");
            }else if(sysUserList.size() == 1) {
                if(!sysUser.getUserId().equals(sysUserList.get(0).getUserId())){
                    //不是自己
                    throw new Exception("sysUser.editUser.accountWarningOrg");
                }
            }


            sysUser.setTenantId(sysOrg.getTenantId());

            this.sysUserDao.update(sysUser);
            //更新状态获取被修改人orgId
//            SysOrg sysOrg = sysOrgService.getSysOrgById(userId);
//            orgId = sysOrg.getOrgId();
        }

        //添加岗位信息
        this.userPositionService.addUserPosition(userId, orgId, null, null, null, sysUser.getPrimayOrgId(), sysUser.getIsCharge());
        //添加上下级信息
        this.userUnderService.addUserSuperior(userId,superiorIds);
        if(isAdd && loadIm){
            String sql = "insert into "+SystemConst.IM_CONNECTION_TABLE+" (ID,USER_ID,USER_NAME,AVATAR)" +
                    "values('"+ UUIDUtils.getUUIDFor32() + "','" + userId + "','" + sysUser.getFullName() + "','/imStatic/pictures/userDefault.jpg')";
            jdbcTemplate.execute(sql);
        }
    }

    public List<SysUser> findByAccountAndTenantId(String account, String tenantId){
        return sysUserDao.findByAccountAndTenantId(account, tenantId);
    }

    /**
     * 初始化三员人员
     * @param sysOrg 组织model
     */
    @Transactional(rollbackFor = Exception.class)
    public void addThreeMember(SysOrg sysOrg) throws Exception {
        String[] threeMember = {SysUser.DEFAULT_XTGLY, SysUser.DEFAULT_AQBMGLY, SysUser.DEFAULT_AQSJY};
        String[] threeMemberName = {SysUser.DEFAULT_XTGLY_NAME, SysUser.DEFAULT_AQBMGLY_NAME, SysUser.DEFAULT_AQSJY_NAME};
        String[] threeMemberRole = {"","",""};
        List<SysRole> threeRole = this.sysRoleService.queryThreeMemberRole(null);
        //写代码时先初始化三员角色后再创建三员人员
        if(threeRole.isEmpty()){
            throw new Exception("初始化时请先初始化三员角色！");
        }
        for(SysRole sysRole : threeRole){
            if(sysRole.getRoleType().equals(SysRole.DEFAULT_XTGLY)){
                threeMemberRole[0] = sysRole.getRoleId();
            }else if(sysRole.getRoleType().equals(SysRole.DEFAULT_AQBMGLY)){
                threeMemberRole[1] = sysRole.getRoleId();
            }else if(sysRole.getRoleType().equals(SysRole.DEFAULT_AQSJY)){
                threeMemberRole[2] = sysRole.getRoleId();
            }
        }
        SysUser sysUser = new SysUser();
        String orgCode = sysOrg.getCode();
        sysUser.setTenantId(sysOrg.getTenantId());
        sysUser.setOrgId(sysOrg.getOrgId());
        sysUser.setPrimayOrgId(sysOrg.getOrgId());
        UserRole userRole = new UserRole();
        //默认三员的密级为系统密级
        Integer systemSec = propertyService.getIntByAlias("systemSec", SysUser.DEFAULT_PRIVACYLEVEL);
        for(int i=0;i<threeMember.length;i++){
            sysUser.setUserId(null);
            sysUser.setPrivacyLevel(systemSec);
            sysUser.setPassword(SysUser.DEFAULT_PASS_WORD);
            sysUser.setAccount(orgCode+threeMember[i]);
            sysUser.setFullName(orgCode+threeMemberName[i]);
            saveUser(sysUser);
            userRole.setUserRoleId(UUIDUtils.getUUIDFor32());
            userRole.setRoleId(threeMemberRole[i]);
            userRole.setUserId(sysUser.getUserId());
            this.userRoleService.add(userRole);
        }
    }

    /**
     * 查询列表
     * @param queryFilter 条件filter
     * @return list
     */
    public List<SysUser> list(QueryFilter queryFilter){
         SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        if (!queryFilter.containsKey("dataPrivacyLevel")) {
            int privacyLevel = sysUser.getPrivacyLevel();
            queryFilter.put("privacyLevel", privacyLevel);
        }
        if(StringUtil.isEmpty(queryFilter.get("orgId"))&& !SystemConst.SUPER_ADMIN_ID.equals(sysUser.getUserId())){
            String currOrgId = ContextUtil.getCurrentOrgId();
            SysOrg sysOrg = sysOrgService.getOneById(currOrgId);
            String path = StringUtil.isNotEmpty(sysOrg.getPath()) ? (sysOrg.getPath() + StringPool.PERCENT) : "";
            queryFilter.put("path", path);
        } else {
            SysOrg sysOrg = sysOrgService.getOneById((String) queryFilter.get("orgId"));
            String path = StringUtil.isNotEmpty(sysOrg.getPath()) ? (sysOrg.getPath() + StringPool.PERCENT) : "";
            queryFilter.put("path", path);
            queryFilter.remove("orgId");
        }
        return sysUserDao.queryUsersByOrg(queryFilter);
    }

    /**
     * 根据条件查询用户
     * @param queryFilter 条件filter
     * @return  list
     */
    public List<SysUser> userSelectorQueryList(QueryFilter queryFilter){
        String roleId = (String)queryFilter.get("roleId");
        SysOrg sysOrg = sysOrgService.getOrgByRoleId(roleId);
        String path = StringUtil.isNotEmpty(sysOrg.getPath()) ? (sysOrg.getPath() + StringPool.PERCENT) : "";
        queryFilter.put("path", path);
        queryFilter.put("isLock",SysUser.UN_LOCKED);
        queryFilter.put("status",SysUser.STATUS_OK);
        return  this.sysUserDao.queryUsersByOrg(queryFilter);
    }

    /**
     * 更新登录异常次数
     * @param userId        用户id
     * @param missNumber    异常次数
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateMissNumber(String userId,Short missNumber){
        Map<String,Object> param = new HashMap<>(2);
        param.put("userId",userId);
        param.put("missNumber",missNumber);
        this.sysUserDao.updateMissNumber(param);
    }
    /**
     * 更新用户在线状态
     * @param userId        用户id
     * @param isOnline      在线状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void upOnlineStatusById(String userId,Short isOnline){
        Map<String,Object> param = new HashMap<>(2);
        param.put("userId",userId);
        param.put("isOnline",isOnline);
        this.sysUserDao.upOnlineStatusById(param);
    }
    /**
     * 更新用户ip
     * @param userId   用户id
     * @param ip       ip
     */
    @Transactional(rollbackFor = Exception.class)
    public void updCurrIpById(String userId,String ip){
        Map<String,Object> param = new HashMap<>(2);
        param.put("userId",userId);
        param.put("currIp", ip);
        this.sysUserDao.updCurrIpById(param);
    }

    /**
     * 是否锁定
     * @param userId 用户id
     * @param isLock  0未锁定  1已锁定
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateIsLock(String userId,Short isLock){
        Map<String,Object> param = new HashMap<>(2);
        param.put("userId",userId);
        param.put("isLock",isLock);
        this.sysUserDao.updateIsLock(param);
    }

    /**
     * 根据id查询用户
     * @param startUserId
     * @return list
     */
    public SysUser getById(String startUserId){
        return this.sysUserDao.getById(startUserId);
    }

    /**
     * 根据用户id查询用户姓名
     * @param ids id数组
     * @return list
     */
    public List<String> queryUserNameByUserIds(String[] ids){
        if(BeanUtils.isEmpty(ids)){
            return null;
        }
        return this.sysUserDao.queryUserNameByUserIds(Arrays.asList(ids));
    }

    /**
     * 根据角色Id查询用户
     * @param roleId 角色id
     * @return 用户列表
     */
    public List<SysUser> queryUserListByRoleId(String roleId) {
        return sysUserDao.queryByRoleId(roleId);
    }

    /**
     * 根据组织id查询用户列表
     * @param orgId 组织id
     * @return 用户列表
     */
    public List<SysUser> queryUserListByOrgId(String orgId) {
        return sysUserDao.queryByOrgId(orgId);
    }

    public List<SysUser> getByAccounts(String accounts){
        String[] account = accounts.split(",");
        return sysUserDao.getByAccounts(Arrays.asList(account));
    }

    /**
     * 根据身份证号查询用户信息
     * @param idCard
     * @return
     */
    public SysUser getByIdCard(String idCard) {
        return sysUserDao.getByIdCard(idCard);
    }

    public String impuserExcel(MultipartFile file) throws Exception {
        String resultMsg = "";
        List<SysUser> insertUser = new ArrayList<SysUser>();//需要插入的用户集合
        String tenanId = ContextUtil.getCurrentUserTenantId();
        SysOrg tenantOrg = sysOrgService.getTenantOrgByTenantId(tenanId);//获取租户的四位码code
        String tenantOrgCode = tenantOrg.getCode();

        InputStream inp = null;
        try {

            inp = (FileInputStream) file.getInputStream();

        } catch (Exception e) {
            inp = (ByteArrayInputStream) file.getInputStream();
        }
        HSSFWorkbook excel = new HSSFWorkbook(inp);
        HSSFSheet sheet = excel.getSheetAt(0);


        List<Dictionary> rymjList = dictionaryService.getByNodeKey("rymj");
        Map<String, Dictionary> rymjMap = CollectionUtils.listToStrMap(rymjList, Dictionary.class, "itemName");

        Iterator it = sheet.rowIterator(); // 小页中所有的数据行对象
        //System.out.println(sheet.getLastRowNum());
        int i = 0;
        if (it.hasNext()) {
            it.next();//先下移一行，因为第一行表示表字段
        }
        Map<String, SysOrg> orgAddMap = new HashMap<>();
        while (it.hasNext()) {
            HSSFRow row = (HSSFRow) it.next();
            HSSFCell cell0 = row.getCell(0);
            HSSFCell cell1 = row.getCell(1);
            HSSFCell cell2 = row.getCell(2);
            HSSFCell cell3 = row.getCell(3);
            HSSFCell cell4 = row.getCell(4);
            HSSFCell cell5 = row.getCell(5);
            HSSFCell cell6 = row.getCell(6);
            HSSFCell cell7 = row.getCell(7);
            HSSFCell cell8 = row.getCell(8);
            HSSFCell cell9 = row.getCell(9);
            HSSFCell cell10 = row.getCell(10);
            SysUser sysUser = new SysUser();//需要插入的用户
            if (cell0 != null) {
                cell0.setCellType(CellType.STRING);
                String code = cell0.getStringCellValue();
                if (!tenantOrgCode.equals(code)) {
                    resultMsg = "导入用户数据不成功，组织代码与当前租户组织代码不匹配。";
                    return resultMsg;
                }
            } else {
                resultMsg = "导入用户数据不成功，组织机构码不允许为空。";
            }
            if (cell1 != null) {//登录账号
                cell1.setCellType(CellType.STRING);
                sysUser.setAccount(cell1.getStringCellValue());
            }
            if (cell2 != null) {//用户名
                cell2.setCellType(CellType.STRING);
                sysUser.setFullName(cell2.getStringCellValue());
            }
            if (cell4 != null) {//身份证
                cell4.setCellType(CellType.STRING);
                sysUser.setIdCard(cell4.getStringCellValue());
            }
            if (cell5 != null) {//密级
                cell5.setCellType(CellType.STRING);
                String key = cell5.getStringCellValue();

                Dictionary dictionary = rymjMap.get(key);

                String privacyLevel = dictionary != null ? dictionary.getItemValue() :"0";

                sysUser.setPrivacyLevel(Integer.parseInt(privacyLevel));
            }
            if (cell6 != null) {//性别
                cell6.setCellType(CellType.STRING);
                String sex = cell6.getStringCellValue();
                switch (sex) {
                    case "男":
                        sysUser.setSex("1");
                        break;
                    case "女":
                        sysUser.setSex("0");
                        break;
                }
            }
            if (cell7 != null) {//排序
                cell7.setCellType(CellType.STRING);
                String number = cell7.getStringCellValue();
                Integer SortNumber = 0;
                if (StringUtil.isNotEmpty(number)) {
                    SortNumber = Integer.parseInt(number);
                }
                sysUser.setSortNumber(SortNumber);
            }
            if (cell8 != null) {//邮件
                cell8.setCellType(CellType.STRING);
                sysUser.setEmail(cell8.getStringCellValue());
            }
            if (cell9 != null) {//移动电话
                cell9.setCellType(CellType.STRING);
                sysUser.setMobile(cell9.getStringCellValue());
            }
            if (cell10 != null) {//电话
                cell10.setCellType(CellType.STRING);
                sysUser.setPhone(cell10.getStringCellValue());
            }

            if (cell3 != null) {//所属组织
                cell3.setCellType(CellType.STRING);
                String orgNames = cell3.getStringCellValue();
                String[] orgArray = orgNames.split("/");
                SysOrg parentOrg = new SysOrg();



                for (int n = 0; n < orgArray.length; n++) {
                    String impOrgName = orgArray[n];
                    if (n == 0) {
                        //判断该组织的一级部门是否存在
                        List<SysOrg> IsOrg = sysOrgService.queryTenantByOrgName(impOrgName, tenanId);

                        parentOrg = initOrgAndGetParent(impOrgName, tenantOrg, IsOrg, orgAddMap);
                    } else {
                        //判断组织的下级部门是否存在
                        List<SysOrg> IsOrg = sysOrgService.queryOrgByorgSupId(impOrgName, parentOrg.getOrgId());
                        parentOrg = initOrgAndGetParent(impOrgName, tenantOrg, IsOrg, orgAddMap);
                    }
                }
                sysUser.setTenantId(tenanId);
                sysUser.setPrimayOrgId(parentOrg.getOrgId());
                sysUser.setOrgId(parentOrg.getOrgId());
                sysUser.setPassword("123456");
            }
            insertUser.add(sysUser);
        }
        if (orgAddMap.keySet().size() > 0) {

            for (String orgName : orgAddMap.keySet()) {
                sysOrgService.add(orgAddMap.get(orgName));
            }
        }

        if (insertUser.size() > 0) {
            String msg = "";//反馈导入失败的用户
            for (SysUser user : insertUser) {
                try {
                    saveUser(user);
                } catch (Exception e) {
                    msg += "【" + user.getFullName() + "】";
                }
            }
            if (!"".equals(msg)) {
                resultMsg = "用户：" + msg + "导入失败，请核实用户信息是否冲突";
            }
        }


        return resultMsg;
    }

    private SysOrg initOrgAndGetParent(String impOrgName, SysOrg tenantOrg, List<SysOrg> IsOrg, Map<String, SysOrg> orgAddMap){

        if (IsOrg.size() == 0) {
            SysOrg sysOrg = orgAddMap.get(impOrgName);
            if(sysOrg == null){
                sysOrg = new SysOrg();//需要插入的组织
                String insertOrgId = UUIDUtils.getUUIDFor32();
                sysOrg.setOrgId(insertOrgId);
                sysOrg.setOrgName(impOrgName);
                sysOrg.setOrgSupId(tenantOrg.getOrgId());
                sysOrg.setDemId(tenantOrg.getDemId());
                sysOrg.setCreatorId(ContextUtil.getCurrentUserId());
                sysOrg.setPath(tenantOrg.getPath() + "." + insertOrgId);
                sysOrg.setOrgPathname(tenantOrg.getOrgPathname() + "/" + impOrgName);

                sysOrg.setTenantId(tenantOrg.getTenantId());
                orgAddMap.put(impOrgName, sysOrg);
            }
            return sysOrg;
        } else {
            return IsOrg.get(0);
        }
    }

    /**
     * 用户数据导出
     */
    public ByteArrayOutputStream outputExcel(List<SysUser> list) throws IOException {
        //String tenanId = ContextUtil.getCurrentUserTenantId();
        //SysOrg tenantOrg = sysOrgService.getTenantOrgByTenantId(tenanId);//获取租户的四位码code
        //String tenantOrgCode = tenantOrg.getCode();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFCellStyle style = hssfWorkbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);

        HSSFSheet sheet = hssfWorkbook.createSheet("用户信息");
        sheet.createFreezePane(0, 1, 0, 1);
        //创建表头
        String[] head = {"组织机构码（四位码）", "用户账号", "用户姓名", "组织机构名称", " 身份证号", "密级 ", "性别 ", "排序", "邮件 ", "移动电话", "电话"};//单位, 部门 ,处室  ,姓名, 职务 办公电话 手机号码 工作手机  房间号  住宅电话 传真
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < head.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(head[i]);
        }



        List<Dictionary> rymjList = dictionaryService.getByNodeKey("rymj");
        Map<String, Dictionary> rymjMap = CollectionUtils.listToStrMap(rymjList, Dictionary.class, "itemValue");

        List<String> userIds = CollectionUtils.getStringPropertys(list, SysUser.class, "userId");

        List<UserPosition> upList = userPositionService.queryPrimaryOrgByUserIds(userIds);

        for (SysUser sysUser : list){
            for (UserPosition up : upList){
                if(up.getUserId().equals(sysUser.getUserId())){
                    sysUser.setOrgId(up.getOrgId());
                    break;
                }
            }
        }

        List<String> orgIds = CollectionUtils.getStringPropertys(list, SysUser.class, "orgId");

        List<SysOrg> orgs = sysOrgService.queryOrgsByOrdIds(orgIds);

        //orgId为key  org 为value
        Map<String, SysOrg> orgMap = CollectionUtils.listToStrMap(orgs, SysOrg.class, "orgId");

        List<String> tenantIds = CollectionUtils.getStringPropertys(orgs, SysOrg.class, "tenantId");

        List<SysOrg> tenantOrgs = sysOrgService.queryTenantOrgByTentanIds(tenantIds);

        //租户Id为Key  org为value
        Map<String, SysOrg> orgTanentMap = CollectionUtils.listToStrMap(tenantOrgs, SysOrg.class, "tenantId");

        for (int i = 0; i < list.size(); i++) {
            HSSFRow rows = sheet.createRow(i + 1);
            SysUser user = list.get(i);
            HSSFCell cell = rows.createCell(0);
            //cell.setCellValue(isNullString(tenantOrgCode));
            cell.setCellValue(orgTanentMap.get(user.getTenantId()).getCode());
            cell = rows.createCell(1);
            cell.setCellValue(isNullString(user.getAccount()));
            cell = rows.createCell(2);
            cell.setCellValue(isNullString(user.getFullName()));
            cell = rows.createCell(3);
            cell.setCellValue(isNullString(getOrgName(orgMap.get(user.getOrgId()), orgTanentMap.get(user.getTenantId()))));
            cell = rows.createCell(4);
            cell.setCellValue(isNullString(user.getIdCard()));
            cell = rows.createCell(5);
            String privacyLevel = rymjMap.get(user.getPrivacyLevel()+"").getItemName();
            cell.setCellValue(isNullString(privacyLevel));
            cell = rows.createCell(6);
            String sex = user.getSex();
            if (StringUtil.isNotEmpty(sex)) {
                switch (sex) {
                    case "1":
                        sex = "男";
                    case "0":
                        sex = "女";
                }
            }
            cell.setCellValue(isNullString(sex));
            cell = rows.createCell(7);
            cell.setCellValue(isNullString(user.getSortNumber()));
            cell = rows.createCell(8);
            cell.setCellValue(isNullString(user.getEmail()));
            cell = rows.createCell(9);
            cell.setCellValue(isNullString(user.getMobile()));
            cell = rows.createCell(10);
            cell.setCellValue(isNullString(user.getPhone()));
        }
        hssfWorkbook.write(outputStream);
        return outputStream;
    }
    private String isNullString(Object object) {
        if (object != null && !(object.toString().equals("") || object.toString().equals("无"))) {
            return object.toString();
        }
        return "";
    }
    public String getOrgName(SysOrg org, SysOrg tenantOrg) {
        //SysOrg sysOrg = sysOrgService.getOrgById(orgId);
        String orgPathName = org.getOrgPathname();
        String tenantOrgPathName = tenantOrg.getOrgPathname();
        String orgName = orgPathName.replace(tenantOrgPathName, "");
        if (StringUtil.isEmpty(orgName)) {
            orgName = tenantOrg.getOrgName();
        } else {
            orgName = tenantOrg.getOrgName() + orgName;
        }
        return orgName;
    }

    @Transactional(rollbackFor = Exception.class)
    public void moveUser(String[] lAryId, String orgId) throws Exception{

        SysOrg sysOrg = sysOrgService.getSysOrgById(orgId);

        List<String> userIds = new ArrayList<>();


        for (String userId : lAryId) {

            boolean isContain = this.sysRoleService.isContainThreeRole(userId);
            if (isContain) {
                continue;
            }
            userIds.add(userId);
        }
        if(userIds.size() == 0) {
            return;
        }
        //待移动用户
        List<SysUser> userList = this.findByUserIds(userIds);

        List<String> accounts = CollectionUtils.getStringPropertys(userList, SysUser.class, "account");
        List<SysUser> oldUserList = this.findByAccountsAndTenantId(accounts, sysOrg.getTenantId());

        boolean flag = true;

        for(SysUser sysUser : userList){
            for(SysUser old : oldUserList){
                //帐户相同，但是userId不同
                if(sysUser.getAccount().equals(old.getAccount()) && !sysUser.getUserId().equals(old.getUserId())){
                    flag = false;
                    break;
                }
            }
            if(!flag){
                break;
            }
        }

        if(!flag){
            //存在相同账户，不让移动
            throw new Exception("sysUser.editUser.accountWarningOrg");
        }

        //批量更新用户租户ID
        sysUserDao.batchUpdateUserTenantId(userIds, sysOrg.getTenantId());
        //批量删除岗位关系
        this.userPositionService.batchDeleteByUserId(userIds);
        List<UserPosition> userPositionList = new ArrayList<>();
        for(String userId : userIds){
            UserPosition userPosition = new UserPosition();
            userPosition.setUserPosId(UUIDUtils.getUUIDFor32());
            userPosition.setUserId(userId);
            userPosition.setOrgId(orgId);
            userPosition.setIsCharge(UserPosition.CHARRGE_NO);
            userPosition.setIsPrimary(UserPosition.PRIMARY_YES);
            userPosition.setIsDelete(UserPosition.DELETE_NO);
            System.out.println(userPosition);
            userPositionList.add(userPosition);
        }

        this.userPositionService.addList(userPositionList);
    }

    public List<SysUser> findByAccountsAndTenantId(List<String> accounts, String tenantId) {
        return this.sysUserDao.findByAccountsAndTenantId(accounts, tenantId);
    }

    public List<SysUser> findByUserIds(List<String> userIds) {
        return this.sysUserDao.findByUserIds(userIds);
    }

    /**
     * 更新用户排序
     *
     * @param userId     用户id
     * @param sortNumber 用户排序
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSortNumber(String userId, Integer sortNumber) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("userId", userId);
        param.put("sortNumber", sortNumber);
        this.sysUserDao.updateSortNumber(param);
    }
}
